package top.kaoshanji.p1ch02b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.p1ch02b.exception.GreetException;
import top.kaoshanji.p1ch02b.exception.GreetRuntimeException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/12/23 20:49
 */
public class GreetAdapter implements InvocationHandler {

    private static final Logger logger = LogManager.getLogger(GreetAdapter.class);

    private GreetV1 greetV1;

    public GreetAdapter(GreetV1 greetV1) {
        this.greetV1 = greetV1;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String methodName = method.getName();
        logger.info("...methodName:{}...", methodName);

        if ("greet".equals(methodName)) {
            String userName = (String) args[0];
            String name = findName(userName);
            String gender = findGender(userName);

            try {
                Method greetMethodV1 = GreetV1.class.getMethod(methodName, new Class<?>[]{String.class, String.class});
                return greetMethodV1.invoke(greetV1, new Object[]{name, gender});
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause != null && cause instanceof GreetException) {
                    throw new GreetRuntimeException(cause);
                }
                throw e;
            }

        } else {
            return method.invoke(greetV1, args);
        }

    }


    private String findGender(String userName) {
        return Math.random() > 0.5 ? userName : null;
    }

    private String findName(String userName) {
        return userName;
    }

}
